<?php
namespace app\admin\controller;

use app\common\lib\CryptoJsAes;
use app\common\model\AdminMenuModel;
use app\common\model\AdminUserModel;

/**
 * 登录控制器
 * @author 贺强
 * @time   2021-06-21 11:51:27
 */
class Login extends Common
{
    /**
     * 登录页
     * @author 贺强
     * @time   2021-06-21 11:52:00
     * @return \think\response\View
     */
    public function index()
    {
        if ($this->request->get('action') === 'logout') {
            session('admin', null);
        }
        $salt = env('app.aes_salt', '258369471xcvn019');
        $iv = env('app.aes_iv', 'y9shd1pdrwvapq8b');
        return view('index2', compact('salt', 'iv'));
    }

    /**
     * 登录
     * @author 贺强
     * @time   2021-06-21 13:52:54
     */
    public function dologin()
    {
        $param = $this->request->post();
        if (empty($param['username']) || empty($param['pwd'])) {
            return ajax('用户名或密码不能为空', 101);
        }
        $time = time();
        $un = $param['username'];
        $admin = AdminUserModel::getModel(['username' => $un], ['id', 'username', 'name', 'password', 'status', 'role_id', 'avatar', 'is_ip'], '', 0);
        if (empty($admin)) {
            return ajax('用户名或密码错误', 102);
        }
        if ($admin['is_ip']) {
            $is_ip = AdminMenuModel::getFieldValue('is_hide', ['identity' => 'admin_ips'], '', 0);
            if (!$is_ip) {
                return ajax('无权访问', 104);
            }
        }
        $salt = env('app.aes_salt', '258369471xcvn019');
        $iv = env('app.aes_iv', 'y9shd1pdrwvapq8b');
        $pwd1 = CryptoJsAes::decryptT($param['pwd'], $salt, $iv);
        $pwd2 = get_md5_password($pwd1);
        $flag = password_verify($pwd1, $admin['password']) || $pwd2 === $admin['password'];
        if (!$flag) {
            return ajax('用户名或密码错误', 103);
        }
        if ($admin['status'] !== 1) {
            return ajax('账号审核不通过或被禁用，请联系管理员', 104);
        }
        $ip = get_client_ip();
        unset($admin['status']);
        // 赋值登录时间和登录IP
        $admin['login_time'] = $time;
        $admin['login_ip'] = $ip;
        $admin['data'] = json_encode($param);
        event('AdminLogin', $admin); // 登录成功后记录登录时间和IP
        // 赋值登录时间和登录IP结束
        session('admin', $admin['id']);
        return ajax('登录成功');
    }
}
